package com.ikingtech.platform.service.push.dingtalk;

import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.push.dingtalk.dto.DeliverResult;
import com.ikingtech.platform.service.push.dingtalk.dto.DingTalkSendMessageDTO;
import com.ikingtech.platform.service.push.dingtalk.service.DingTalkService;
import com.ikingtech.platform.service.push.dingtalk.service.RobotInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * created on 2023-05-24 16:25
 *
 * @author wub
 */

@Slf4j
@Service
public class DingTalkDeliver {

    private final DingTalkService dingTalkService;

    private final Map<String, RobotInterface> robotInterfaceMap;

    @Autowired
    public DingTalkDeliver(List<RobotInterface> implementations, DingTalkService dingTalkService) {
        this.dingTalkService = dingTalkService;
        robotInterfaceMap = new HashMap<>();
        for (RobotInterface impl : implementations) {
            robotInterfaceMap.put(impl.getType(), impl);
        }
    }

    public R<DeliverResult> sendRobotMessage(DingTalkSendMessageDTO dto) {
        try {
            return R.ok(dingTalkService.sendMessage(dto));
        } catch (Exception e) {
            //记录或者处理
            log.error(Tools.Str.format("dingTalk send message failed, message:{}, error:{}", Tools.Json.toJsonStr(dto), e.getMessage()));
        }
        return R.ok(new DeliverResult(false, "dingTalk消息发送失败"));
    }

    public R<DeliverResult> sendRobotMessage(String payLoad, String type) {
        RobotInterface robotInterface = robotInterfaceMap.get(type);
        if (robotInterface != null) {
            DingTalkSendMessageDTO dto;
            try {
                dto = robotInterface.analysis(payLoad);
            } catch (Exception e) {
                return R.ok(new DeliverResult(false, "解析失败,请检查参数"));
            }
            return this.sendRobotMessage(dto);
        } else {
            return R.ok(new DeliverResult(false, "接收到机器人解析消息,但找不到指定的实现类"));
        }
    }
}
